package com.flyme.module.file.provider.listener;

import com.flyme.module.file.client.entity.SysLive;
import com.flyme.module.file.client.event.PoylEvent;
import com.flyme.module.file.provider.service.SysLiveService;
import com.flyme.module.file.provider.service.impl.SysLiveServiceImpl;
import com.flyme.module.file.provider.utils.PolyvUtil;
import com.flyme.module.file.provider.utils.PoylUtil2;
import com.polyv.live.bean.result.channel.PLChannelCreateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class PlylListener implements SmartApplicationListener {


    @Autowired
    private SysLiveService liveService;

    /**
     * 只有监听类型匹配才执行
     */
    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventClass) {
        return eventClass == PoylEvent.class;
    }

    /**
     * SysLiveServiceImpl
     */
    @Override
    public boolean supportsSourceType(Class<?> aClass) {
        return aClass == SysLiveServiceImpl.class;
    }

    /**
     * 业务逻辑
     */
    @Override
    @Async
    public void onApplicationEvent(ApplicationEvent applicationEvent) {

        // 转换事件类型
        PoylEvent poylEvent = (PoylEvent) applicationEvent;
        Integer type = poylEvent.getType();
        List<String> ids = poylEvent.getIds();
        // 获取注册用户对象信息
        if (type.equals(1)) {
            Long userId = poylEvent.getUserId();
            SysLive live = poylEvent.getLive();
            addChannel(live, userId);
        }
        if (type.equals(2)) {
            delChannel(ids);
        }
    }

    private Boolean addChannel(SysLive live, Long userId) {
        PLChannelCreateResult channelCreateResult = PoylUtil2.crateChannel(live.getLiveTitle(), live.getScene());
        live.setChannelId(channelCreateResult.getChannelId());
        liveService.saveOrUpdate(live);
        return true;
    }

    private Boolean delChannel(List<String> ids) {
        for (String id : ids) {
            PolyvUtil.delChannel(new Integer(id));
        }
        return true;
    }

    /**
     * 同步情况下监听执行的顺序
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
